<template>
	<div class="captcha_div">
		<lazy-slide-captcha
			ref="captcha"
			:width="width"
			:height="height"
			:show-refresh="true"
			:fail-tip="failTip"
			:success-tip="successTip"
			@finish="handleFinish"
			@refresh="generate"
			@onsuccess="onsuccess"
		>
		</lazy-slide-captcha>
	</div>
</template>

<script>
import LazySlideCaptcha from "../../../components/lazySlideCaptcha/index.vue";
// import "lazy-slide-captcha/dist/lazy-slide-captcha.css";
export default {
	components: {
		LazySlideCaptcha,
	},
	name: "Captcha",
	props: {
		msg: String,
	},
	data() {
		return {
			requestId: undefined,
			failTip: "",
			successTip: "",
			// width，height保持与552 * 344同比例即可
			width: 400,
			height: 250,
			// width: 340,
			// height: 212,
			// width: 552,
			// height: 344,
		};
	},
	mounted() {
		this.generate();
	},
	methods: {
		async generate() {
			this.$nextTick(async () => {
				// 改变内部状态，标识生成请求开始
				this.$refs.captcha.startRequestGenerate();
				//获取验证码
				var response = await this.$API.auth.captcha
					.get()
					.catch((error) => {
						console.log(error);
						// 标识生成请求结束
						this.$refs.captcha.endRequestGenerate(null, null);
					});
				if (response.code == 200) {
					this.requestId = response.data.id;
					// 改变内部状态，标识生成请求结束，同时设定background，slider图像
					this.$refs.captcha.endRequestGenerate(
						response.data.backgroundImage,
						response.data.sliderImage
					);
				}
			});
		},
		async handleFinish(data) {
			// 改变内部状态，标识验证请求开始
			this.$refs.captcha.startRequestVerify();
			//获取验证码
			var response = await this.$API.auth.captchaCheck
				.post(this.requestId, data)
				.catch((error) => {
					console.log(error);
					this.failTip = "服务异常，请稍后重试";
					// 标识验证请求结束
					this.$refs.captcha.endRequestVerify(false);
				});
			if (response.code == 200) {
				let success = response.data === 0;
				// 验证失败时显示信息
				this.failTip =
					response.data == 1
						? "验证未通过，拖动滑块将悬浮图像正确合并"
						: "验证超时, 请重新操作";
				// 验证通过时显示信息
				this.successTip = "验证通过，超过80%用户";
				// 改变内部状态，标识验证请求结束，同时设定是否成功状态
				this.$refs.captcha.endRequestVerify(success);
				this.$emit("onsuccess", success);
				if (!success) {
					setTimeout(() => {
						this.generate();
					}, 1000);
				}
			}
		},
	},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
